﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WorkBasket.Data.Entities;
using WorkBasket.Data.Repository;
using WorkBasket.Infrastructure;
using WorkBasket.Models;

namespace WorkBasket.Controllers.Api
{
    [Authorize]
    public class FormControlController : ApiController
    {
        private SOC soc = new SOC(new MyContext());

        [HttpPost]
        [Route("api/formcontrol/save")]
        public IHttpActionResult Post([FromBody] FormControl value)
        {
            try
            {
                if (value.FormControlID == 0)
                {
                    soc.FormControls.Add(value);
                }
                else
                {
                    soc.FormControls.Update(value);
                }

                soc.CommitChanges();
                return Json(new DataReturn(value.ControlName +  " Saved", value));
            }
            catch (Exception e)
            {
                return new System.Web.Http.Results.ExceptionResult(e, this);
            }
        }
        [HttpGet]
        [Route("api/formcontrol/ControlsJsonFormat/{FormID}")]
        public IHttpActionResult ControlsJsonFormat(int FormID)
        {
            return Json(soc.Execute<TreeNode>("ControlsJsonFormat @FormID", new SqlParameter("FormID", FormID)));
        }
        [Route("api/formcontrol/GetByKey/{ID}")]
        public IHttpActionResult GetByKey(int id)
        {
            return Json(soc.FormControls.GetByID(id));

        }

        [HttpPost]
        [Route("api/formcontrol/delete")]
        public IHttpActionResult Delete([FromBody] FormControl value)
        {
            try
            {
                soc.FormControls.Delete(value.FormControlID);
                soc.CommitChanges();
                return Json(new DataReturn("Control Deleted", value));
            }
            catch (Exception e)
            {
                return new System.Web.Http.Results.ExceptionResult(e, this);
            }
        }
    }
}
